//
//  MessageListViewController.m
//  BGM
//
//  Created by 我要变好看 on 2018/12/18.
//  Copyright © 2018 com.alirtc.demo. All rights reserved.
//

#import "MessageListViewController.h"
#import "BGMHTTP.h"
#import "Common.h"
#import "BGMUser.h"
#import "MessageTableViewCell.h"
#import "MessageAcceptViewController.h"
#import "CommonViewController.h"
#import "MJRefresh.h"
#import "SVProgressHUD.h"
#import "RewardSuccess.h"
#import "CommonView.h"

@interface MessageListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)NSString *type;
@property (nonatomic, strong)UITableView *messageTable;
@property (nonatomic, strong)NSMutableArray *messageArray;
@property (nonatomic, assign)int currentPage;

@end

@implementation MessageListViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    CGRect rect = self.titleBtn.frame;
    rect.size.width = rect.size.width+70;
    self.titleBtn.frame = rect;
    switch (self.maeesgeType) {
        case 1:
        {
            [self.titleBtn setTitle:@"帮忙消息" forState:UIControlStateNormal];
            self.type = @"PUBLISH_MESSAGE";
        }
            break;
        case 2:
        {
            [self.titleBtn setTitle:@"系统通知" forState:UIControlStateNormal];
            self.type = @"SYSTEM_MESSAGE";


        }
            break;
        case 3:
        {
            [self.titleBtn setTitle:@"答谢通知" forState:UIControlStateNormal];
            self.type = @"THANK_MESSAGE";

        }
            break;

        default:
            break;
    }
    
    self.messageArray = [[NSMutableArray alloc]init];
    
    self.messageTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-self.navview.frame.size.height)];
    self.messageTable.delegate = self;
    self.messageTable.dataSource = self;
    [self.view addSubview:self.messageTable];
        [self setExtraCellLineHidden:self.messageTable];
    
    
    self.messageTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.messageArray removeAllObjects];
        self.currentPage = 1;
        [self requestMessageList];
    }];
    
    self.messageTable.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.currentPage==0) {
            [self.messageTable.mj_footer endRefreshing];
        }else{
            [self requestMessageList];
        }
    }];
    
    [self.messageTable.mj_header beginRefreshing];
 
    
}

-(void)setExtraCellLineHidden: (UITableView *)tableView

{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

- (void)requestMessageList{
    NSString *userToken = [BGMUser shareInstance].userToken;
    NSString *userId = [BGMUser shareInstance].userId;

    NSDictionary *param = @{@"userToken":userToken,
                            @"userId":userId,
                            @"pushType":self.type,
                            @"pageNum":[NSString stringWithFormat:@"%d",self.currentPage],
                            @"pageSize":@"10"
                            };
    [BGMHTTP requestWithMethodName:@"message/getPushMessageList" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSArray *array = [result objectForKey:@"data"];
        [self reloadTableView:array];
    }];
}

- (void)reloadTableView:(NSArray *)array{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.messageTable.mj_header endRefreshing];
        [self.messageTable.mj_footer endRefreshing];
        
        if (array.count==10) {
            self.currentPage = self.currentPage +1;
        }else{
            self.currentPage = 0;
        }
        [self.messageArray addObjectsFromArray:array];
        [self.messageTable reloadData];
        
        if (self.messageArray.count == 0) {
            self.mormalLabel.hidden = NO;
            self.messageTable.hidden = YES;
        }else{
            self.mormalLabel.hidden = YES;
            self.messageTable.hidden = NO;
        }
        
    });
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.messageArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return 70;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"MessageTableViewCell";
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell ==nil) {
        cell = [[MessageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSDictionary *dic = [self.messageArray objectAtIndex:indexPath.row];
    [cell messageIno:dic];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = [self.messageArray objectAtIndex:(int)indexPath.row];
    NSString *type = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareThree"]];
    NSString *notid = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];;
    [self changeMessageStatus:notid];
    
    if ([type isEqualToString:@"notice_of_action"]) {  //受理
        MessageAcceptViewController *vc = [[MessageAcceptViewController alloc]init];
        vc.pushMessageId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([type isEqualToString:@"comment"]){
        
        CommonViewController *vc = [[CommonViewController alloc]init];
        vc.publishId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareOne"]];//发布id
        vc.userId =[NSString stringWithFormat:@"%@",[dic objectForKey:@"pushUsersId"]];  //发布者iD
        vc.publishHelpUserId = @"";
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if ([type isEqualToString:@"getRed_package"]){  //领取帮转红包
        NSString *status = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareTwo"]];  //1未读 2已读
        
        if ([status isEqualToString:@"1"]) {
            [self showRewardSuccess:dic];
            [self getRedpackage:dic indexPath:indexPath];
        }else{
            [self showMoney:dic];
        }
    }else if ([type isEqualToString:@"thank_you"]){  //答谢
        NSString *status = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareTwo"]];  //1未读 2已读
       
        if ([status isEqualToString:@"1"]) {
            [self showRewardSuccess:dic];
            [self getThank:dic indexPath:indexPath];
        }else{
            [self showMoney:dic];

        }
    }
    
    MessageTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.readStatus.hidden = YES;
    
}
- (void)showMoney:(NSDictionary *)dic{
    NSString *type = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareThree"]];
    if ([type isEqualToString:@"getRed_package"]){  //帮转红包
        NSString *str = [NSString stringWithFormat:@"已经成功领取帮转红包 %@ 元",[dic objectForKey:@"spareOne"]];
        UIAlertController *al = [CommonView getCommonAlert:@"" message:str ok:@"确定" cancel:@"取消" completed:^(NSInteger index) {
        }];
        [self presentViewController:al animated:YES completion:nil];
    }else if ([type isEqualToString:@"thank_you"]){  //答谢红包
        NSString *str = [NSString stringWithFormat:@"已经成功领取答谢金%@元",[dic objectForKey:@"spareOne"]];
        UIAlertController *al = [CommonView getCommonAlert:@"" message:str ok:@"确定" cancel:@"取消" completed:^(NSInteger index) {
        }];
        [self presentViewController:al animated:YES completion:nil];
    }
    
}

#pragma mark 答谢红包
- (void)getThank:(NSDictionary *)redDic indexPath:(NSIndexPath *)indexPath{
    NSString *notId = [NSString stringWithFormat:@"%@",[redDic objectForKey:@"id"]];
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"usersId":[BGMUser shareInstance].userId,@"pushMessageId":notId};
    [BGMHTTP requestWithMethodName:@"message/getAnserRedPacakge" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if ([code isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:@"领取成功"];
                MessageTableViewCell *cell = [self.messageTable cellForRowAtIndexPath:indexPath];
                [cell.helpImage setImage:[UIImage imageNamed:@"norMoney"]];
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:redDic];
                [dic setObject:@"2" forKey:@"spareTwo"];
                [self.messageArray replaceObjectAtIndex:indexPath.row withObject:dic];
            
                
            });
        }
    }];
}
#pragma mark 领取帮转红包
- (void)getRedpackage:(NSDictionary *)redDic indexPath:(NSIndexPath *)indexPath{
    NSString *notId = [NSString stringWithFormat:@"%@",[redDic objectForKey:@"id"]];
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"usersId":[BGMUser shareInstance].userId,@"pushMessageId":notId};
    [BGMHTTP requestWithMethodName:@"message/getRedPacakge" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if ([code isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:@"领取成功"];
                MessageTableViewCell *cell = [self.messageTable cellForRowAtIndexPath:indexPath];
                [cell.helpImage setImage:[UIImage imageNamed:@"norMoney"]];
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:redDic];
                [dic setObject:@"2" forKey:@"spareTwo"];
                [self.messageArray replaceObjectAtIndex:indexPath.row withObject:dic];
                
            });
        }
    }];
}
#pragma mark 通知已读
- (void)changeMessageStatus:(NSString *)notiiD{
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"usersId":[BGMUser shareInstance].userId,@"messageId":notiiD};
    [BGMHTTP requestWithMethodName:@"message/changePushMessageState" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
     }];
}
- (void)showRewardSuccess:(NSDictionary *)dic{
    NSString *str = [NSString stringWithFormat:@"成功领取 %@ 元",[dic objectForKey:@"spareOne"]];
     [RewardSuccess showString:str];
}


@end
